import * as readline from "readline"
//控制台与参数操作

//文件操作
import * as fs from "fs"



//呼叫进程打开浏览器
import * as c from 'child_process'
import { FormatMgr } from "./format/formatmgr"
import { Server } from "./server/server"

async function MainAsync() {
    let conasync = readline.promises.createInterface(process.stdin, process.stdout);

    //处理Ctrl_C
    conasync.on("close", () => {
        process.exit(0);
        return;
    });


    if (process.argv.length <= 2) {
        console.log("参数不够")
        process.exit(0);
        return;
    }

    let filename = process.argv[2];
    console.log("argv:" + filename);
    try {
        fs.statSync(filename);
    }
    catch {
        console.warn("文件不存在");
        process.exit(0);
    }
    let debug = true;
    if (process.argv.length > 3 && process.argv[3] == "autoclose") {
        debug = false;
    }

    let format = FormatMgr.Instance().GetFormatInfo(filename);
    if (format == null) {
        console.warn("不能处理的文件格式");
        process.exit(0);
    }


    let server = new Server();
    server.Start(format, filename, debug);

    c.exec("start http://127.0.0.1:" + server.GetPort());

    console.warn("***关键进程,请勿主动关闭,否则可能丢失数据***")

    while (true) {

        let p = await conasync.question("");
        if (p == "exit") {
            process.exit(0);
        }
        console.log("host at http://127.0.0.1:" + server.GetPort())
    }
}

MainAsync();

